#!/bin/bash
set -x
DT="group_faction_edges"
DT2="invest_page_rank"
NEW_DT="jtpx_cs"
REMOTEDIR=/home/work/changsha_project/jtpx_data
DATADIR=/home/dig/graph_data/algorithm_data/changsha
CONSISTENCE_FILE="cs_jtpx_file_md5.txt"
REMOTE_ADDR=172.18.180.228


if [ ! -d ${DATADIR}/${DT} -o ! -d ${DATADIR}/${DT2} ]; then
    echo "data not ready"
    exit 0
fi

# 计算md5
cd ${DATADIR}/${DT}
dt_md5=`ls -lt |md5sum |  awk '{print $1}'`
cd ${DATADIR}/${DT2}
dt2_md5=`ls -lt |md5sum |  awk '{print $1}'`

cs_md5=${dt_md5}${dt2_md5}

old_cs_md5=''
if [ -f ${DATADIR}/${CONSISTENCE_FILE} ]; then
    old_cs_md5=`cat ${DATADIR}/${CONSISTENCE_FILE}`
fi

if [ "$cs_md5" == "$old_cs_md5" ]; then
    echo "version is the same,exit: md5 = ${cs_md5}"
    exit 0
fi

cd ${DATADIR}
rm ${NEW_DT}.tgz
tar -zcf ${NEW_DT}.tgz ${DT} ${DT2}

# 压缩文件计算md5
#cs_md5=`cat ${NEW_DT}.tgz | md5sum | awk '{print $1}'`
#if [ "$cs_md5" == "$old_cs_md5" ]; then
#    echo "version is the same,exit"
#    exit 0
#fi

echo "当前MD5: ${cs_md5}"
echo "旧版MD5: ${old_cs_md5}"

echo -n ${cs_md5} > ${CONSISTENCE_FILE}

# 重新计算压缩包MD5
tar_md5=`cat ${NEW_DT}.tgz | md5sum | awk '{print $1}'`

try_cnt=0
while [ ${try_cnt} -lt 4 ];
do
    scp ${NEW_DT}.tgz work@${REMOTE_ADDR}:${REMOTEDIR}/
    result=`ssh work@${REMOTE_ADDR} "sh" ${REMOTEDIR}"/cat_cs_jtpx_md5.sh"`
    if [ "${tar_md5}" != "${result}" ];then
        echo "sync file failed"
    else
        # 发送MD5文件
        ssh work@${REMOTE_ADDR} "echo ${tar_md5} > ${REMOTEDIR}/${NEW_DT}.md5"
        break
    fi
    try_cnt=`expr ${try_cnt} + 1`
    if [ ${try_cnt} -ge 4 ];then
        echo "jtpx 数据传输失败了: ${NEW_DT}.tgz"
        exit -1
    fi
done

ssh work@${REMOTE_ADDR} "sh" ${REMOTEDIR}"/upload_jtpx_data_to_changsha.sh"
